﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;

using BEGDC.Utility.Castle;
using BEGDC.Utility.ExceptionManagement;
using BEGDC.CC.BL.Common.Query;
using BEGDC.CC.BL.Workflow;
using BEGDC.CC.BL.UserManagement;
using BEGDC.CC.BL.Common;
//using GDC.CODM.Entity;
using BEGDC.CC.Web.UserControls;
using NetBpm.Util.Client;
using NetBpm.Workflow.Execution;
using NetBpm.Workflow.Execution.EComp;

namespace BEGDC.CC.Web.Workflow
{
	/// <summary>
	/// Summary description for MyTaskList.
	/// </summary>
	public class MyTaskList : System.Web.UI.Page
	{
		#region variable define
		protected System.Web.UI.WebControls.PlaceHolder MainBody;
		protected System.Web.UI.WebControls.Label lblPriority;
		protected System.Web.UI.WebControls.Label lblStatus;
		protected System.Web.UI.WebControls.Label lblAPN;
		protected System.Web.UI.WebControls.Label lbTotalCount;
		protected System.Web.UI.WebControls.DropDownList ddlPriority;
		protected System.Web.UI.WebControls.DropDownList ddlStatus;
		protected System.Web.UI.WebControls.TextBox txtAPN;
		protected System.Web.UI.WebControls.DataGrid dgSearch;
		protected System.Web.UI.WebControls.ImageButton btnSearch;
		protected System.Web.UI.WebControls.ImageButton btnTQSample;
		protected System.Web.UI.WebControls.ImageButton btnIQSample;
		protected System.Web.UI.WebControls.ImageButton btnReceiveSample;
		protected System.Web.UI.WebControls.ImageButton btnExport;
		protected System.Web.UI.WebControls.ImageButton btnPrint;
		protected System.Web.UI.WebControls.TextBox tbShowTQSample;
		protected System.Web.UI.WebControls.TextBox tbShowIQSample;
		protected System.Web.UI.WebControls.TextBox tbShowPrintForm;
		protected System.Web.UI.WebControls.TextBox tbShowSampleReceive;
		protected System.Web.UI.WebControls.Label lblSampleStatus;
		protected System.Web.UI.WebControls.DropDownList ddlSampleStatus; 
		protected System.Web.UI.WebControls.ImageButton btnPageFirst;
		protected System.Web.UI.WebControls.ImageButton btnPageNext;
		protected System.Web.UI.WebControls.ImageButton btnPagePrev;
		protected System.Web.UI.WebControls.ImageButton btnPageLast;
		protected System.Web.UI.HtmlControls.HtmlTable tblPageNavi;
		protected System.Web.UI.HtmlControls.HtmlGenericControl spnPageFooter;


		private DataTable taskListSource;

		private DataTable CachedFilterTable
		{
			set
			{
				Session["cachedFilterTable"] = value;
			}
			get
			{
				if(Session["cachedFilterTable"] == null)
					return null;
				return (DataTable)Session["cachedFilterTable"];
			}
		}

		private DataTable CachedColumnTable
		{
			set
			{
				ViewState["cachedColumnTable"] = value;
			}
			get
			{
				if(ViewState["cachedColumnTable"] == null)
					return null;
				return (DataTable)ViewState["cachedColumnTable"];
			}
		}

		private int PriorityIndex
		{
			set
			{
				ViewState["priorityIndex"] = value;
			}
			get
			{
				if(ViewState["priorityIndex"] == null)
					return -1;
				return (int)ViewState["priorityIndex"];
			}
		}

		private string SortExpression
		{
			set
			{
				ViewState["sortExpression"] = value;
			}
			get
			{
				if(ViewState["sortExpression"] == null)
					return string.Empty;
				return (string)ViewState["sortExpression"];
			}
		}

		private string CheckedProjectList
		{
			set
			{
				ViewState["checkedProjectList"] = value;
			}
			get
			{
				if(ViewState["checkedProjectList"] == null)
					return string.Empty;
				return (string)ViewState["checkedProjectList"];
			}
		}

		private bool CheckAll
		{
			set
			{
				ViewState["checkAll"] = value;
			}
			get
			{
				if(ViewState["checkAll"] == null)
					return false;
				return (bool)ViewState["checkAll"];
			}
		}
		private int _PageCount
		{
			get
			{
				if( ViewState["PageCount"] != null ) return (int) ViewState["PageCount"];
				else
					return 0;
			}
			set
			{
				ViewState["PageCount"] = value;
			}
		}
		private int _CurrentPageIndex
		{
			get
			{
				if( ViewState["CurrentPageIndex"] != null ) return (int) ViewState["CurrentPageIndex"];
				else
					return 0;
			}
			set
			{
				ViewState["CurrentPageIndex"] = value;
			}
		}
		private int _RowCount
		{
			get
			{
				if( ViewState["RowCount"] != null ) return (int) ViewState["RowCount"];
				else
					return 0;
			}
			set
			{
				ViewState["RowCount"] = value;
			}
		}
		#endregion

		private void Page_Load(object sender, System.EventArgs e)
		{
			try
			{
				// Put user code to initialize the page here
				if(!Page.IsPostBack)
				{
					InitializeGlobalization();
//					InitializeDropDownList();
					this.BindData();
				}
				this.tbShowTQSample.Text = string.Empty;
				this.tbShowIQSample.Text = string.Empty;
				this.tbShowPrintForm.Text = string.Empty;
				this.tbShowSampleReceive.Text = string.Empty;
			}
			catch(GDCException gdcEx)
			{
//				WebUtility.Go2ErrorPage(this.Page, gdcEx.ErrorNumber);
			}
			catch(Exception ex)
			{
				string s = ex.Message;
//				WebUtility.Go2ErrorPage(this.Page, BEGDC.CC.BL.Common.ErrorCode.Other_Exception);
			}
		}

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{    
//			this.btnSearch.Click += new System.Web.UI.ImageClickEventHandler(this.btnSearch_Click);
			this.dgSearch.SortCommand += new DataGridSortCommandEventHandler(dgSearch_SortCommand);
			this.dgSearch.ItemDataBound += new DataGridItemEventHandler(dgSearch_ItemDataBound);
			this.dgSearch.PageIndexChanged += new System.Web.UI.WebControls.DataGridPageChangedEventHandler(this.dgSearch_PageIndexChanged);
			this.dgSearch.ItemCommand += new DataGridCommandEventHandler(dgSearch_ItemCommand);
			this.dgSearch.ItemCreated += new DataGridItemEventHandler(dgSearch_ItemCreated);
			this.btnTQSample.Click += new System.Web.UI.ImageClickEventHandler(this.btnTQSample_Click);
			this.btnIQSample.Click += new System.Web.UI.ImageClickEventHandler(this.btnIQSample_Click);
			this.btnReceiveSample.Click += new System.Web.UI.ImageClickEventHandler(this.btnReceiveSample_Click);
			this.btnExport.Click += new System.Web.UI.ImageClickEventHandler(this.btnExport_Click);
			this.btnPrint.Click += new System.Web.UI.ImageClickEventHandler(this.btnPrint_Click);
			this.Load += new System.EventHandler(this.Page_Load);
			this.btnPageFirst.Click += new System.Web.UI.ImageClickEventHandler(this.btnPageFirst_Click);
			this.btnPagePrev.Click += new System.Web.UI.ImageClickEventHandler(this.btnPagePrev_Click);
			this.btnPageNext.Click += new System.Web.UI.ImageClickEventHandler(this.btnPageNext_Click);
			this.btnPageLast.Click += new System.Web.UI.ImageClickEventHandler(this.btnPageLast_Click);
			InitialDataGridColumn();
		}
		#endregion

		private void InitializeGlobalization()
		{
			
		}

		private void InitializeDropDownList()
		{
			IUtility utility = AppContainer.Instance[ServiceConst.UtilityService] as IUtility;
			IList list = utility.BuildDicList("priority");
			
			this.ddlPriority.DataTextField = "Text";
			this.ddlPriority.DataValueField = "Value";
			this.ddlPriority.DataSource = list;
			this.ddlPriority.DataBind();
			
			IList list1 = utility.BuildDicList("prj_status");
			
			this.ddlStatus.DataTextField = "Text";
			this.ddlStatus.DataValueField = "Value";
			this.ddlStatus.DataSource = list;
			this.ddlStatus.DataBind();

			IList list2 = utility.BuildDicList("free_sample_status");
			
			this.ddlSampleStatus.DataTextField = "KeyValue";
			this.ddlSampleStatus.DataValueField = "KeyValue";
			this.ddlSampleStatus.DataSource = list2;
			this.ddlSampleStatus.DataBind();

			this.ddlPriority.Items.Insert(0,new ListItem("All", "All"));
			this.ddlStatus.Items.Insert(0,new ListItem("All", "All"));
			this.ddlSampleStatus.Items.Insert(0,new ListItem("All", "All"));
		}

		private void InitialDataGridColumn()
		{
			int totalWidth = 0;
			if(this.CachedColumnTable == null)
			{
				CCIdentity id = this.User.Identity as CCIdentity;
				IUser iuser = AppContainer.Instance[ServiceConst.UserService] as IUser;
//				IList list = iuser.GetUserList();
//				int a = 1;
//				this.CachedColumnTable = iuser.GetUserColumn(id.UserInfo.Id);
			}

			if(this.CachedColumnTable != null)
			{
				for(int i=0; i<this.CachedColumnTable.Rows.Count; i++)
				{
					string column = this.CachedColumnTable.Rows[i]["KeyValue"].ToString();
					
					if(column != string.Empty)
					{
						if(column == "APN")
						{
							TemplateColumn tc = new TemplateColumn();
							tc.ItemTemplate = new APNTemplateColumn();
							tc.HeaderText = WebUtility.ConvertStatusString(column);
							tc.ItemStyle.Width = WebUtility.GetColumnWidth(column);
							tc.ItemStyle.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Center;
							this.dgSearch.Columns.Add(tc);
						}
						else if (column == "StatusFlag")
						{
							TemplateColumn tc = new TemplateColumn();
							tc.ItemTemplate = new StatusFlagColumn();
							tc.HeaderText = WebUtility.ConvertStatusString(column);
							tc.ItemStyle.Width = WebUtility.GetColumnWidth(column);
							tc.ItemStyle.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Center;
							this.dgSearch.Columns.Add(tc);
						}
						else
						{
							BoundColumn col = new BoundColumn();
							col.DataField = column;
							col.HeaderText = WebUtility.ConvertStatusString(column);

//							if(col.DataField == "DR2Date" || col.DataField == "RegisterDate" || col.DataField == "TQPlanDate"
//								|| col.DataField == "TQDate" | col.DataField == "IQDate" | col.DataField == "CQDate")
//								col.DataFormatString = "{0:"+GDC.CODM.Resource.CommonString.DateFormat+"}";
//							else if(col.DataField == "PriorityText")
//								this.PriorityIndex = i+5;
							col.SortExpression = column;
							col.ItemStyle.Width = WebUtility.GetColumnWidth(column);
							col.ItemStyle.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Center;
							this.dgSearch.Columns.Add(col);
						}
						totalWidth += WebUtility.GetColumnWidth(column);
					}
				}
				
				if(totalWidth < 630)
					totalWidth = 630;
				this.dgSearch.Width = totalWidth+150;
			}
		}

		private void BindData()
		{
//			IExecute executionComponent = BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.CC.BL.Common.ServiceConst.ExecuteService] as IExecute;
//			IList tasks = executionComponent.GetTaskList();
//			if (tasks == null || tasks.Count == 0)
//				return;
//
//			string flowids = string.Empty;
//			foreach(long taskid in tasks)
//			{
//				if(flowids.Length > 0)
//					flowids += "," + taskid.ToString();
//				else
//					flowids += taskid.ToString();
//			}
			
			IQuery iquery = AppContainer.Instance[ServiceConst.QueryService] as IQuery;
			//this.taskListSource = iquery.QueryTaskList(((CCIdentity)HttpContext.Current.User.Identity).UserInfo.Id, BEGDC.CC.BL.Workflow.WorkflowTypes.CV);

			RefreshDataGrid();

			SetPageCount();
		}

		private string GetDisplayName(string name)
		{
			return name.Substring(name.IndexOf(",")+1);
		}

		private string GetFieldName(string name)
		{
			return name.Substring(0,name.IndexOf(","));
		}

//		private void btnSearch_Click(object sender, System.Web.UI.ImageClickEventArgs e)
//		{
//			try
//			{
//				this.dgSearch.CurrentPageIndex = 0;
//				string condition = string.Empty;
//				if(this.ddlPriority.SelectedValue != "All")
//					condition += " PriorityText = '"+this.ddlPriority.SelectedValue+"' ";
//				if(this.ddlStatus.SelectedValue != "All")
//					if(condition.Length > 0)
//						condition += " and ProjectStatus = '"+this.ddlStatus.SelectedItem.Text+"'";
//					else
//						condition += " ProjectStatus = '"+this.ddlStatus.SelectedItem.Text+"'";
//				if(this.txtAPN.Text.Trim() != string.Empty)
//					if(condition.Length > 0)
//						condition += " and APN like '%"+this.txtAPN.Text+"%'";
//					else
//						condition += " APN like '%"+this.txtAPN.Text+"%'";
//
//				this.btnReceiveSample.Visible = false;
//				this.dgSearch.Columns[0].Visible = false;
//				this.btnIQSample.Visible = false;
//				this.btnTQSample.Visible = false;
//				if(this.ddlStatus.SelectedValue == "IQSend")
//				{
//					this.btnIQSample.Visible = true;
//					this.dgSearch.Columns[0].Visible = true;
//					this.lblSampleStatus.Visible = false;
//					this.ddlSampleStatus.Visible = false;
//				}
//				else if(this.ddlStatus.SelectedValue == "TQSend")
//				{
//					this.btnTQSample.Visible = true;
//					this.dgSearch.Columns[0].Visible = true;
//					this.lblSampleStatus.Visible = false;
//					this.ddlSampleStatus.Visible = false;
//				}
//				else if(this.ddlStatus.SelectedValue == "IQReview" || this.ddlStatus.SelectedValue == "TQFirstReview")
//				{
//					if(this.ddlSampleStatus.SelectedValue.ToUpper() != "ALL")
//					{
//						if(condition.Length > 0)
//							condition += " and FreeSampleStatus = '"+this.ddlSampleStatus.SelectedValue+"'";
//						else
//							condition += " FreeSampleStatus = '"+this.ddlSampleStatus.SelectedValue+"'";
//					}
//
//					if(this.ddlSampleStatus.SelectedValue.ToUpper() == "WAITING")
//					{
//						this.dgSearch.Columns[0].Visible = true;
//						this.btnReceiveSample.Visible = true;
//					}
//					this.lblSampleStatus.Visible = true;
//					this.ddlSampleStatus.Visible = true;
//				}
//				else
//				{
//					this.lblSampleStatus.Visible = false;
//					this.ddlSampleStatus.Visible = false;
//				}
//
//				DataRow[] rows = this.CachedTable.Select(condition);
//				DataTable table = this.CachedTable.Copy();
//				table.Rows.Clear();
//				for(int i=0; i<rows.Length; i++)
//				{
//					DataRow row = table.NewRow();
//					for(int j=0; j<table.Columns.Count; j++)
//						row[j] = rows[i][j];
//					table.Rows.Add(row);
//				}
//
//				this.CachedFilterTable = table;
//				RefreshDataGrid();
//				SetPageCount();
//			}
//			catch(GDCException gdcEx)
//			{
//				WebUtility.Go2ErrorPage(this.Page, gdcEx.ErrorNumber);
//			}
//			catch
//			{
//				WebUtility.Go2ErrorPage(this.Page, BEGDC.CC.BL.Common.ErrorCode.Other_Exception);
//			}
//		}
//
		
		private void dgSearch_PageIndexChanged(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
		{
			try
			{
				SetCheckedProjectList();
				this.dgSearch.CurrentPageIndex = e.NewPageIndex;
				RefreshDataGrid();
			}
			catch(GDCException gdcEx)
			{
				WebUtility.Go2ErrorPage(this.Page, gdcEx.ErrorNumber);
			}
			catch
			{
				WebUtility.Go2ErrorPage(this.Page, BEGDC.CC.BL.Common.ErrorCode.Other_Exception);
			}
		}

		private void dgSearch_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
		{
			try
			{
				if(e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
				{
					if(this.PriorityIndex >= 0)
					{
						if(e.Item.Cells[this.PriorityIndex].Text.Trim().ToUpper() == "HIGH")
							e.Item.Cells[this.PriorityIndex].ForeColor = Color.Red;
//						e.Item.Cells[this.PriorityIndex].Text = GDC.CODM.Resource.Workflow.Keys.GetString(e.Item.Cells[this.PriorityIndex].Text);
					}
				
					if(this.dgSearch.Columns[0].Visible)
					{
		　　			if(this.CheckedProjectList.IndexOf(e.Item.Cells[1].Text+",") >= 0 )
						{
							CheckBox chk = (CheckBox)e.Item.FindControl("chbSelect");
							chk.Checked = true;
						}
					}

					string demoId = e.Item.Cells[1].Text;
					string demoStatus = e.Item.Cells[2].Text;
					HyperLink  link = (HyperLink)e.Item.Cells[3].Controls[0];
					link.NavigateUrl = string.Format("{0}/DemoWorkflow/WorkflowExecution.aspx?DemoId={1}", BEGDC.CC.Web.UserControls.WebUtility.Path, demoId);
				}
				else if(e.Item.ItemType == ListItemType.Header)
				{
					CheckBox chk = (CheckBox)e.Item.FindControl("chbAll");
					chk.Checked = this.CheckAll;
				}
			}
			catch(GDCException gdcEx)
			{
//				WebUtility.Go2ErrorPage(this.Page, gdcEx.ErrorNumber);
			}
			catch
			{
//				WebUtility.Go2ErrorPage(this.Page, BEGDC.CC.BL.Common.ErrorCode.Other_Exception);
			}
		}

		private void RefreshDataGrid()
		{
			this.lbTotalCount.Text = "Total:"+this.taskListSource.Rows.Count.ToString();

			this.dgSearch.DataSource = taskListSource;
			this.dgSearch.DataBind();
		}

		private void btnTQSample_Click(object sender, System.Web.UI.ImageClickEventArgs e)
		{
			try
			{
				SetCheckedProjectList();
				RefreshDataGrid();
				Session["CheckedProjectList"] = this.CheckedProjectList;
				this.tbShowTQSample.Text = "Yes";
			}
			catch(GDCException gdcEx)
			{
//				WebUtility.Go2ErrorPage(this.Page, gdcEx.ErrorNumber);
			}
			catch
			{
//				WebUtility.Go2ErrorPage(this.Page, BEGDC.CC.BL.Common.ErrorCode.Other_Exception);
			}
		}

		private void btnIQSample_Click(object sender, System.Web.UI.ImageClickEventArgs e)
		{
			try
			{
				SetCheckedProjectList();
				RefreshDataGrid();
				Session["CheckedProjectList"] = this.CheckedProjectList;
				this.tbShowIQSample.Text = "Yes";
			}
			catch(GDCException gdcEx)
			{
				WebUtility.Go2ErrorPage(this.Page, gdcEx.ErrorNumber);
			}
			catch
			{
				WebUtility.Go2ErrorPage(this.Page, BEGDC.CC.BL.Common.ErrorCode.Other_Exception);
			}
		}

		private void btnReceiveSample_Click(object sender, System.Web.UI.ImageClickEventArgs e)
		{
			try
			{
				SetCheckedProjectList();
				RefreshDataGrid();
				Session["CheckedProjectList"] = this.CheckedProjectList;
				this.tbShowSampleReceive.Text = this.ddlStatus.SelectedValue;
			}
			catch(GDCException gdcEx)
			{
				WebUtility.Go2ErrorPage(this.Page, gdcEx.ErrorNumber);
			}
			catch
			{
				WebUtility.Go2ErrorPage(this.Page, BEGDC.CC.BL.Common.ErrorCode.Other_Exception);
			}
		}

		private void btnExport_Click(object sender, System.Web.UI.ImageClickEventArgs e)
		{
			try
			{
				RefreshDataGrid();
				this.GenerateExcelFile();
			}
			catch(GDCException gdcEx)
			{
				WebUtility.Go2ErrorPage(this.Page, gdcEx.ErrorNumber);
			}
//			catch(Exception ex)
//			{
//				WebUtility.Go2ErrorPage(this.Page, BEGDC.CC.BL.Common.ErrorCode.Other_Exception);
//			}
		}

		private void btnPrint_Click(object sender, System.Web.UI.ImageClickEventArgs e)
		{
			try
			{
				RefreshDataGrid();
				Session["PrintDataGrid"] = this.CachedFilterTable;
				this.tbShowPrintForm.Text = "Yes";
			}
			catch(GDCException gdcEx)
			{
				WebUtility.Go2ErrorPage(this.Page, gdcEx.ErrorNumber);
			}
			catch
			{
				WebUtility.Go2ErrorPage(this.Page, BEGDC.CC.BL.Common.ErrorCode.Other_Exception);
			}
		}

		private void dgSearch_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
		{
			try
			{
				//RefreshDataGrid();
				if(e.CommandName == "Action")
				{
//					IUser iuser = AppContainer.Instance[ServiceConst.UserService] as IUser;
					int projectID = Convert.ToInt32(e.Item.Cells[1].Text);
					string status = e.Item.Cells[2].Text;
					string qualNo = e.Item.Cells[3].Text;
					WebUtility.RedirectToExecution(projectID, qualNo, status);
				}
			}
			catch(GDCException gdcEx)
			{
				WebUtility.Go2ErrorPage(this.Page, gdcEx.ErrorNumber);
			}
			catch
			{
				WebUtility.Go2ErrorPage(this.Page, BEGDC.CC.BL.Common.ErrorCode.Other_Exception);
			}
		}

		public void dgSearch_SortCommand(Object sender, DataGridSortCommandEventArgs e)
		{ 
			try
			{
				string sortExpression = this.SortExpression;
				string sortDeriction = "ASC";
				string lastColumn = string.Empty;
				if(sortExpression != string.Empty)
				{
					lastColumn = sortExpression.Substring(0, sortExpression.IndexOf(","));
					sortDeriction = sortExpression.Substring(sortExpression.IndexOf(",")+1);
					if(lastColumn == e.SortExpression)
					{
						if(sortDeriction == "ASC")
							sortDeriction = "DESC";
						else
							sortDeriction = "ASC";
					}
				}
				// Create a DataView from the DataTable.
				DataView dv = new DataView(this.CachedFilterTable);

				// The DataView provides an easy way to sort. Simply set the
				// Sort property with the name of the field to sort by.
				dv.Sort = e.SortExpression+" "+sortDeriction;
				this.SortExpression = e.SortExpression+","+sortDeriction;

				// Re-bind the data source and specify that it should be sorted
				// by the field specified in the SortExpression property.
				this.dgSearch.DataSource = dv;
				this.dgSearch.DataBind();
			}
			catch(GDCException gdcEx)
			{
				WebUtility.Go2ErrorPage(this.Page, gdcEx.ErrorNumber);
			}
			catch
			{
				WebUtility.Go2ErrorPage(this.Page, BEGDC.CC.BL.Common.ErrorCode.Other_Exception);
			}
		}

		private void SetCheckedProjectList()
		{
			if(this.dgSearch.Columns[0].Visible)
			{
				foreach (DataGridItem i in this.dgSearch.Items)
				{ 
		　　		CheckBox chk = (CheckBox)i.FindControl("chbSelect");
					string temp = i.Cells[1].Text + ",";
	　				if(chk.Checked)
					{
						if(this.CheckedProjectList.IndexOf(temp) < 0)
							this.CheckedProjectList += temp;
					}
					else
					{
						if(this.CheckedProjectList.IndexOf(temp) >= 0)
							this.CheckedProjectList = this.CheckedProjectList.Replace(temp,string.Empty);
					}
			　　}
			}
		}

		private void dgSearch_ItemCreated(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e) 
		{ 
			try
			{
　　			if(e.Item.ItemType == ListItemType.Header)
				{ 
　　				CheckBox chk = (CheckBox)e.Item.FindControl("chbAll");
　　				chk.CheckedChanged +=new EventHandler(chk_CheckedChanged);
　　			}
			}
			catch(GDCException gdcEx)
			{
				WebUtility.Go2ErrorPage(this.Page, gdcEx.ErrorNumber);
			}
			catch
			{
				WebUtility.Go2ErrorPage(this.Page, BEGDC.CC.BL.Common.ErrorCode.Other_Exception);
			}
		} 

		private void chk_CheckedChanged(object sender, System.EventArgs e) 
		{ 
			try
			{
　　			CheckBox chk = this.GetHeaderCheckBox(this.dgSearch);
				this.CheckedProjectList = string.Empty;
　　		
				foreach (DataRow row in this.CachedFilterTable.Rows)
				{ 
					if(chk.Checked)
　　				this.CheckedProjectList += row["ProjectID"].ToString()+",";
　　			}
				foreach (DataGridItem i in this.dgSearch.Items)
				{
					CheckBox inChk = (CheckBox)i.FindControl("chbSelect");
　　			inChk.Checked = chk.Checked;
				}

				this.CheckAll = chk.Checked;
			}
			catch(GDCException gdcEx)
			{
				WebUtility.Go2ErrorPage(this.Page, gdcEx.ErrorNumber);
			}
			catch
			{
				WebUtility.Go2ErrorPage(this.Page, BEGDC.CC.BL.Common.ErrorCode.Other_Exception);
			}
		} 

		private CheckBox GetHeaderCheckBox(DataGrid grd)
		{ 
　　		CheckBox chk = null;
　　		foreach (DataGridItem i in grd.Controls[0].Controls)
			{ 
　　			if(i.ItemType == ListItemType.Header)
				{ 
　　				chk = (CheckBox)i.FindControl("chbAll");
　　				break;
　　			} 
　　		} 
　　		return chk;
		} 

		private void GenerateExcelFile()
		{
			try
			{
				DataTable table = this.CachedFilterTable;
				if(table != null)
				{
					StringWriter sw=new StringWriter(); 
					string header = "Qual.No,";
					string content = string.Empty;
					string column;
					for(int i=0; i<this.CachedColumnTable.Rows.Count; i++)
					{
						header += this.CachedColumnTable.Rows[i][1].ToString()+",";
					}
					sw.WriteLine(header.Substring(0,header.Length-1));

					foreach(DataRow dr in table.Rows) 
					{ 
						content = dr["QualNo"]+",";
						for(int i=0; i<this.CachedColumnTable.Rows.Count; i++)
						{
							column = this.CachedColumnTable.Rows[i][1].ToString();
							content += dr[column].ToString().Replace(","," ")+",";
						}
						sw.WriteLine(content.Substring(0,content.Length-1)); 
					} 
					sw.Close(); 
					Response.AddHeader("Content-Disposition", "attachment; filename=FileName.csv"); 
					Response.ContentType = "application/ms-excel"; 
					Response.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312"); 
					Response.Write(sw); 
					Response.End(); 
				}
			}
			catch{}
		}

		#region FormatDateString
		protected string FormatDateString( object dateStr )
		{
			if ( dateStr == DBNull.Value || dateStr == null ) return "";

			return UserControls.WebUtility.FormatDateString( Convert.ToDateTime( dateStr ) );
		}
		#endregion

		#region page navigation
		private void SetPageNavi( int newPage )
		{
			if( newPage <= 1 )
			{
				this.btnPageFirst.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path+"/images/pg_first_inact.gif";
				this.btnPagePrev.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path+"/images/pg_pre_inact.gif";
				this.btnPageFirst.Attributes["disabled"] = "true";
				this.btnPagePrev.Attributes["disabled"] = "true";
			}
			else
			{
				this.btnPageFirst.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path+"/images/pg_first.gif";
				this.btnPagePrev.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path+"/images/pg_pre.gif";
				this.btnPageFirst.Attributes.Remove("disabled");
				this.btnPagePrev.Attributes.Remove("disabled");
			}

			if( newPage >= _PageCount )
			{
				this.btnPageNext.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path+"/images/pg_next_inact.gif";
				this.btnPageLast.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path+"/images/pg_last_inact.gif";
				this.btnPageNext.Attributes["disabled"] = "true";
				this.btnPageLast.Attributes["disabled"] = "true";
			}
			else
			{
				this.btnPageNext.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path+"/images/pg_next.gif";
				this.btnPageLast.ImageUrl = BEGDC.CC.Web.UserControls.WebUtility.Path+"/images/pg_last.gif";
				this.btnPageNext.Attributes.Remove("disabled");
				this.btnPageLast.Attributes.Remove("disabled");
			}

//			this.spnPageFooter.InnerHtml = Resource.CommonString.Keys.GetString( 
//				Resource.CommonString.Keys.ResultPageFooter, 
//				new string[] { _RowCount.ToString(), newPage.ToString(), _PageCount.ToString() } ) ;

			_CurrentPageIndex = newPage;
		}

		private void SetPageCount()
		{
			int count = this.taskListSource.Rows.Count;
			if( count > 0 )
			{
				_RowCount = count;
				_PageCount = count / this.dgSearch.PageSize;
				if( count % this.dgSearch.PageSize > 0) _PageCount ++;
				_CurrentPageIndex = 1;

				SetPageNavi(1);
			}
			else
			{
				_RowCount = count;
				_PageCount = count;
				_CurrentPageIndex = 0;
				SetPageNavi(0);
			}
		}
		#endregion

		#region page event
		private void btnPageFirst_Click(object sender, System.Web.UI.ImageClickEventArgs e)
		{
			try
			{
				if( _CurrentPageIndex == 1 ) return;
				this.dgSearch.CurrentPageIndex = 0;
//				this.dgSearch.DataSource = this.CachedFilterTable;
//				this.dgSearch.DataBind();
				BindSortedDataGrid();
				SetPageNavi(1);
			}
			catch(GDCException gdcEx)
			{
//				WebUtility.Go2ErrorPage(this.Page, gdcEx.ErrorNumber);
			}
			catch
			{
//				WebUtility.Go2ErrorPage(this.Page, BEGDC.CC.BL.Common.ErrorCode.Other_Exception);
			}
		}

		private void btnPagePrev_Click(object sender, System.Web.UI.ImageClickEventArgs e)
		{
			try
			{
				if( _CurrentPageIndex == 1 ) return;
				this.dgSearch.CurrentPageIndex = _CurrentPageIndex-2;
//				this.dgSearch.DataSource = this.CachedFilterTable;
//				this.dgSearch.DataBind();
				BindSortedDataGrid();
				SetPageNavi(_CurrentPageIndex-1);
			}
			catch(GDCException gdcEx)
			{
//				WebUtility.Go2ErrorPage(this.Page, gdcEx.ErrorNumber);
			}
			catch
			{
//				WebUtility.Go2ErrorPage(this.Page, BEGDC.CC.BL.Common.ErrorCode.Other_Exception);
			}
		}

		private void btnPageNext_Click(object sender, System.Web.UI.ImageClickEventArgs e)
		{
			try
			{
				if( _CurrentPageIndex == _PageCount ) return;
				this.dgSearch.CurrentPageIndex = _CurrentPageIndex;
//				this.dgSearch.DataSource = this.CachedFilterTable;
//				this.dgSearch.DataBind();
				BindSortedDataGrid();
				SetPageNavi(_CurrentPageIndex+1);
			}
			catch(GDCException gdcEx)
			{
//				WebUtility.Go2ErrorPage(this.Page, gdcEx.ErrorNumber);
			}
			catch
			{
//				WebUtility.Go2ErrorPage(this.Page, BEGDC.CC.BL.Common.ErrorCode.Other_Exception);
			}
		}

		private void btnPageLast_Click(object sender, System.Web.UI.ImageClickEventArgs e)
		{
			try
			{
				this.dgSearch.CurrentPageIndex = _PageCount-1;
//				this.dgSearch.DataSource = this.CachedFilterTable;
//				this.dgSearch.DataBind();
				BindSortedDataGrid();
				SetPageNavi(_PageCount);
			}
			catch(GDCException gdcEx)
			{
//				WebUtility.Go2ErrorPage(this.Page, gdcEx.ErrorNumber);
			}
			catch
			{
//				WebUtility.Go2ErrorPage(this.Page, BEGDC.CC.BL.Common.ErrorCode.Other_Exception);
			}
		}
		#endregion

		public void BindSortedDataGrid()
		{
			string sortExpression = this.SortExpression;
			string sortDeriction = "ASC";
			string lastColumn = string.Empty;
			DataView dv = new DataView(this.CachedFilterTable);
			if(sortExpression != string.Empty)
			{
				lastColumn = sortExpression.Substring(0, sortExpression.IndexOf(","));
				sortDeriction = sortExpression.Substring(sortExpression.IndexOf(",")+1);
				dv.Sort = lastColumn+" "+sortDeriction;
			}

			this.dgSearch.DataSource = dv;
			this.dgSearch.DataBind();
		}
	}

	public class APNTemplateColumn : ITemplate 
	{ 
		//第一个模板列 
		public void InstantiateIn(System.Web.UI.Control container)       
		{ 
			HtmlTable table = new HtmlTable();
			table.DataBinding += new EventHandler(this.OnDataBinding); 
			table.CellPadding = 0;
			table.CellSpacing = 0;
			table.Width = "95%";
			//数据绑定 
			container.Controls.Add(table); 
		} 

		public void OnDataBinding(object sender, EventArgs e) 
		{ 
//			int pos;
//			string apn, description;
//			HtmlTable table = (HtmlTable) sender;
//			DataGridItem container = (DataGridItem)table.NamingContainer; 
//			string content = ((DataRowView)container.DataItem)["APNDescription"].ToString();
//			string[] apns = content.Split('|');
//			for(int i=0; i<apns.Length; i++)
//			{
//				if(apns[i] == string.Empty)
//					continue;
//				pos = apns[i].IndexOf(",");
//				if(pos >= 0)
//				{
//					apn = apns[i].Substring(0, pos);
//					description = apns[i].Substring(pos+1);
//					if(description == string.Empty)
//						description = "&nbsp;";
//
//					HtmlTableRow row = new HtmlTableRow();
//
//					HtmlTableCell cell = new HtmlTableCell();
//					cell.InnerHtml = apn;
//					cell.Width = "40%";
//					if(i == 0)
//						cell.Attributes.Add("class", "ReportCell"); 
//					else
//						cell.Attributes.Add("class", "ReportCell_lrb"); 
//					row.Cells.Add(cell);
//
//					cell = new HtmlTableCell();
//					cell.InnerHtml = description;
//					cell.Width = "60%";
//					if(i == 0)
//						cell.Attributes.Add("class", "ReportCell_trb"); 
//					else
//						cell.Attributes.Add("class", "ReportCell_rb"); 
//					row.Cells.Add(cell);
//
//					table.Rows.Add(row);
//				}
//			}
		}			
	} 


	public class StatusFlagColumn : ITemplate 
	{ 
		public void InstantiateIn(System.Web.UI.Control container)       
		{ 
			HtmlTable table = new HtmlTable();
			table.DataBinding += new EventHandler(this.OnDataBinding); 
			table.CellPadding = 0;
			table.CellSpacing = 0;
			table.Width = "95%";
			//数据绑定 
			container.Controls.Add(table); 			
		} 

		public void OnDataBinding(object sender, EventArgs e) 
		{ 
			HtmlImage image;
			
			HtmlTable table = (HtmlTable) sender;
			DataGridItem container = (DataGridItem)table.NamingContainer; 
			string statusflag = ((DataRowView)container.DataItem)["StatusFlag"].ToString();
			string changeid = ((DataRowView)container.DataItem)["ChangeID"].ToString();
			string supplierimproveid = ((DataRowView)container.DataItem)["SupplierImproveID"].ToString();

			HtmlTableRow row = new HtmlTableRow();
			HtmlTableCell cell = new HtmlTableCell();
			cell.Align = "Center";

			if(statusflag != string.Empty)
			{
				image = new HtmlImage();
				image.Src = "../Images/"+statusflag+"Flag.gif";
//				image.Alt = WebUtility.ConvertStringByFileInfoResource(statusflag);
				cell.Controls.Add(image);
				System.Web.UI.LiteralControl literal = new LiteralControl("  ");
				cell.Controls.Add(literal);
			}

			if(changeid != string.Empty && changeid != "0")
			{
				image = new HtmlImage();
				image.Src = "../Images/Change.gif";
//				image.Alt = WebUtility.ConvertStringByFileInfoResource("Change");
				cell.Controls.Add(image);
				System.Web.UI.LiteralControl literal = new LiteralControl("  ");
				cell.Controls.Add(literal);
			}

			if(supplierimproveid != string.Empty && supplierimproveid != "0")
			{
				image = new HtmlImage();
				image.Src = "../Images/Improvement.gif";
//				image.Alt = WebUtility.ConvertStringByFileInfoResource("Improvement");
				cell.Controls.Add(image);
			}
			row.Cells.Add(cell);
			table.Rows.Add(row);
		}
		
	}
}
